package com.fcx.workai.jinchang.ui.main;

import android.util.Base64;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider;
import com.alibaba.sdk.android.oss.common.utils.OSSUtils;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.fcx.workai.jinchang.api.ApiFactory;
import com.fcx.workai.jinchang.bean.MyCheckUpdateVersionDTO;
import com.fcx.workai.jinchang.bean.OssUrlBean;
import com.fcx.workai.loginmodule.api.request.Request_RefreshToken;
import com.google.gson.Gson;
import com.hxh.component.basicore.component.mvp.persenter.BasePresenter;
import com.hxh.component.basicore.component.net.BaseAPI;
import com.hxh.component.basicore.component.net.IApiError;
import com.hxh.component.basicore.util.Utils;
import com.hxh.component.basicore.util.rx.RxUtils;
import com.hxh.component.basicore.util.rx.resetfulhttpstyle.ProgressSubScribe;
import com.hxh.component.business.app.App;
import com.hxh.component.business.common.UserInfoBean;
import com.hxh.component.business.ui.bean.UserCompanyListBean;
import com.hxh.component.business.utils.Constant;
import com.hxh.component.business.utils.oss.CallBackBody;
import com.hxh.component.business.utils.oss.api.OssApiService;
import com.hxh.component.business.utils.oss.bean.OssUpLoadResultBean;
import com.hxh.component.business.utils.oss.request.Request_GetOssInfo;
import com.hxh.component.business.utils.oss.response.InitOssResponse;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

import static com.hxh.component.business.utils.Constant.TENANT_ID;

/**
 * Created by mardawang on 2017/11/6.
 */

public class MainActivityPresenter extends BasePresenter<MainActivity> implements MainActivityContract.P{


    @Override
    public void refreshToken() {
        final String mTenantId ;
        String baseUrl = com.hxh.component.business.BuildConfig.AUTH_ENDPOINT;
        if ("https://api.workai.com.cn/".equals(baseUrl) || "http://120.55.17.174/".equals(baseUrl)){
            mTenantId = Constant.TENANT_ID;
        }else {
            mTenantId = Constant.DEBUF_TENANT_ID;
        }
        addSubscription(
                ApiFactory
                        .getUserCompanyList(true,null)
                        .flatMap(new Func1<UserCompanyListBean, Observable<UserInfoBean>>() {
                            @Override
                            public Observable<UserInfoBean> call(UserCompanyListBean userCompanyListBean)
                            {
                                getView().showJiGouResult(userCompanyListBean);

                                if(userCompanyListBean.getTotal_count() <=0)
                                {
                                    Observable.error(new Throwable(""));
                                }

                                String company_id = Utils.SP.getString(Constant.SpTag.COMPANY_ID);
                                return ApiFactory.refreToken(new Request_RefreshToken(App.getUserDTO().getUser().getRefresh_token(),
//                                        null != App.getUserDTO().getUser().getTenant()?App.getUserDTO().getUser().getTenant().getId():
//                                        company_id!=""?company_id:userCompanyListBean.getItems().get(0).getId()
                                        mTenantId
                                ));
                            }
                        })
                        .subscribe(new ProgressSubScribe<UserInfoBean>(true) {
                            @Override
                            public void _OnError(Throwable msg) {
                                IApiError apiError = getApiError(msg);
                                if(apiError!=null&&apiError.getErrorCode()==401){
                                    getView().showRefreshTokenResult(false);
                                }else if(apiError!=null&&apiError.getErrorCode()==400)
                                {
                                    getView().showRefreshTokenResult(false);
                                }
                            }

                            @Override
                            public void _OnNet(UserInfoBean userInfoBean) {
                                App.getUserDTO().setUser(userInfoBean);
                                getView().showRefreshTokenResult(true);
                            }
                        })
        );
    }

    @Override
    public void checkUpdate() {

        addSubscription(
                ApiFactory.checkAppUpdate("jinchang")
                        .subscribe(new ProgressSubScribe<MyCheckUpdateVersionDTO>(true) {
                            @Override
                            public void _OnError(Throwable msg) {

                            }

                            @Override
                            public void _OnNet(MyCheckUpdateVersionDTO bean) {
                                int currentCode = Utils.Package.getVersionCode();
                                String [] as = bean.getItem().getChange_log().split("\\|");
                                List<String> change = Arrays.asList(as);
                                for (int i = 0; i < change.size(); i++) {
                                    change.set(i,i+1+". "+change.get(i));
                                }
                                if(Integer.valueOf(bean.getItem().getMin_available_version())>currentCode)
                                {
                                    getView().showCheckUpdateResult(Constant.APPUPDATESTATE_FORCE,bean.getItem().getDownload_url(),change);
                                }else if(Integer.valueOf(bean.getItem().getVersion_code())>currentCode)
                                {
                                    getView().showCheckUpdateResult(Constant.APPUPDATESTATE_NOFORCE,bean.getItem().getDownload_url(),change);
                                }else
                                {
                                    getView().showCheckUpdateResult("",bean.getItem().getDownload_url(),change);
                                }
                            }
                        })
        );
    }

    @Override
    public void downLoadAPK(String filePath, FileCallBack callBack) {
        OkHttpUtils.get()
                .url(filePath)
                .build()
                .execute(callBack);
    }

    @Override
    public void getOssUrl() {
        addSubscription(
                ApiFactory
                        .getOssInfo()
                        .subscribe(new ProgressSubScribe<OssUrlBean>() {
                            @Override
                            public void _OnError(Throwable throwable) {

                            }

                            @Override
                            public void _OnNet(OssUrlBean bean) {
                                getView().showOssResult(bean);
                            }
                        })
        );
    }

    public  String loadimage(String tanant_id, String user_id, boolean fromcompanny) {

        String url = "http://hropublic.oss-cn-beijing.aliyuncs.com/user_image/users/"+user_id+".png";
        //String url = "http://hropublic.oss-cn-beijing.aliyuncs.com/user_image/tenants/" + tanant_id + "/users/" + user_id + ".png";

        if (user_id == null ) {

            if (App.getUserDTO().getUser() != null) {
                UserInfoBean.TenantBean ten = App.getUserDTO().getUser().getTenant();
                UserInfoBean.UserBean bean = App.getUserDTO().getUser().getUser();

                if (null != bean)
                {
                    user_id = App.getUserDTO().getUser().getUser().getId();
                }
            }
            url = "http://hropublic.oss-cn-beijing.aliyuncs.com/user_image/users/"+user_id+".png";

            return url;

        } else {

            return url;
        }
    }


    private InitOssResponse initOssResponse;

    public void initOss_default() {
        if (initOssResponse != null) {
            return;
        }
        BaseAPI.getInstance().createServices(App.getUserDTO().getBaseUrl(Constant.APIServicesTag
                .API_APISERVICES), OssApiService.class)
                .getOssInitInfo(new Request_GetOssInfo(Constant.OSSId.OSS_USER_IMAGE, "sdk", ""))
                .compose(RxUtils.<InitOssResponse>io_main())
                .doOnNext(new Action1<InitOssResponse>() {
                    @Override
                    public void call(InitOssResponse rep) {
                        initOssResponse = rep;
                    }
                })
                .subscribe(new Action1<InitOssResponse>() {
                    @Override
                    public void call(InitOssResponse response) {

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    private String uploadFile(final InitOssResponse response, String saveFilePath) {

        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        OSSCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {
            @Override
            public String signContent(String content) {
                // 您需要在这里依照OSS规定的签名算法，实现加签一串字符内容，并把得到的签名传拼接上AccessKeyId后返回
                // 一般实现是，将字符内容post到您的业务服务器，然后返回签名
                // 如果因为某种原因加签失败，描述error信息后，返回nil
                // 以下是用本地算法进行的演示

                return OSSUtils.sign(response.getAccess_key_id(), response.getAccess_key_secret(), content);
            }
        };
        OSS oss = new OSSClient(App.getContext(), endpoint, credentialProvider);
        PutObjectRequest request = new PutObjectRequest(response.getBucket(), response.getObject_path() + ".png", saveFilePath);
        setOssCallBacBody(oss, response, request);
        //request.setMethod(MethodType.POST);
        try {

            PutObjectResult putresult = oss.putObject(request);

            String result = new String(putresult.getServerCallbackReturnBody().getBytes(), "utf-8");
            OssUpLoadResultBean bean = JSON.parseObject(result, OssUpLoadResultBean.class);

            String str = loadimage(null, null, false);
            return str;
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    private void setOssCallBacBody(OSS oss, InitOssResponse initOSSResponse, PutObjectRequest request) {
        String callbackBody = initOSSResponse.getCallback_body();
        String decodedString = new String(Base64.decode(callbackBody.getBytes(), Base64.DEFAULT));
        CallBackBody callBackBody = new Gson().fromJson(decodedString, CallBackBody.class);
        Map<String, String> callbackVars = new HashMap<>();
        callbackVars.put("callbackUrl", callBackBody.callbackUrl);
        callbackVars.put("callbackHost", callBackBody.callbackHost);
        callbackVars.put("callbackBody", callBackBody.callbackBody);
        callbackVars.put("callbackBodyType", callBackBody.callbackBodyType);
        request.setCallbackParam(callbackVars);
        callbackVars = new HashMap<>();
        callbackVars.put("x:access_token", initOSSResponse.getCallback_token());
        request.setCallbackVars(callbackVars);

    }
}
